import {
  $startWuxRefresher,
  $wuxBackdrop,
  $stopWuxRefresher
} from "../../components/lib/index"
const util =require('../../utils/util')
const app=getApp();
let begin=0;
const step=4;
Page({
  retain() {
    this.$wuxBackdrop.retain()
    this.setData({
      locks: this.$wuxBackdrop.backdropHolds,
      showSettings:true
    })
  },
  release() {
    this.$wuxBackdrop.release()
    this.setData({
      locks: this.$wuxBackdrop.backdropHolds,
      showSettings:false
    })
  },
  doNotMove: function () {
    // console.log('stop user scroll it!');
    return;
  },
  switchTheme(e){
    var newTheme={};
    let app=getApp();
    console.log(e.detail)
    if(this.data.btnValue){
      this.setData({
        btnValue:false
      })
      newTheme=app.globalData.themes[0];
      wx.showModal({
        title: '提示',
        content: '重启小程序后生效',
        success (res) {
          if (res.confirm) {
            util.updateDbByOpenId('UserPrivateInfo',app.globalData.userInfo.openId,{theme:0})
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    }else{
      this.setData({
        btnValue:true
      })
      newTheme=app.globalData.themes[1];
      wx.showModal({
        title: '提示',
        content: '重启小程序后生效',
        success (res) {
          if (res.confirm) {
            util.updateDbByOpenId('UserPrivateInfo',app.globalData.userInfo.openId,{theme:1})
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    }
    getApp().globalData.theme=newTheme;
    console.log("当前主题",getApp().globalData.theme)

  },
  navToSearch(){
    wx.navigateTo({
      url: '/pages/search/search',
    })
  },
  /**
   * 页面的初始数据
   */
  data: {
    show:false,
    presentTheme:getApp().globalData.presentTheme,
    themeName:getApp().globalData.presentTheme.lightColor.match(/wux-(\S*)/)[1],
    forRollImage://轮播图
    [
        {imgUrl:"https://shoot.photo/images/2022/02/03/q3bF7.png"},
        {imgUrl:"https://shoot.photo/images/2022/02/03/q3bF7.png"},
        {imgUrl:'https://shoot.photo/images/2022/02/03/q3bF7.png'}
    ],
    noticeList:[
      {title:"这个双11什么护肤品值得买？",url:"https://zhuanlan.zhihu.com/p/425303182"},
      {title:"来测一下你适合什么样的妆容？",url:"http://www.5h.com/mr/161881.html"},
      {title:"皮肤爱出油长痘痘？你可能需要它！",url:"https://www.zhihu.com/question/35189413"},
      {title:"四季补水保湿秘典来啦！",url:"https://zhuanlan.zhihu.com/p/99742737"}],
    articleList:[
    ],
    msg:"",
    data:0,
    scrollTop:0,
    logoUrl:'https://shoot.photo/images/2022/02/03/q3bF7.png',
    userInfo:{
      avatarUrl:'https://shoot.photo/images/2022/02/03/q3bF7.png',//https://636c-cloud1-6g4fn1e1fc689993-1309475441.tcb.qcloud.la/photos/%E7%99%BD%E8%BE%B9%E5%9C%86%E8%A7%92logo.png?sign=e773d7f0b3b6337c6b572ce0a80dd8ba&t=1651971170
      nickName:'',
      openSettings:'openPerson',
      initAccount:'initAccount',
      bgc:getApp().globalData.presentTheme.lightBgColor,
    },
    buttons:[
      {
        label: 'Camera',
        icon:'',
        hideShadow:true,
      },
      {
        label: 'Image',
        icon:'',
        hideShadow:true
      },
      {
        label: 'Create',
        icon:'',
        hideShadow:true
      }
    ]

  },
  //轮播图点击事件
  previewImg:function(res){
    // console.log(res.target.dataset);
    // console.log(res.currentTarget.dataset);
    // console.log(res.currentTarget.dataset['src'])
    let that=this;
    var img=res.currentTarget.dataset['src']
    wx.previewImage({
      current:img, //当前显示图片的http链接
      urls: [that.data.forRollImage[0].imgUrl,// 需要预览的图片http链接列表
      that.data.forRollImage[1].imgUrl,
      that.data.forRollImage[2].imgUrl] 
    })
},
//轮播栏点击事件
bbsNew:function(e){
  var url=e.target.dataset['goto'];
  // console.log(e.target.dataset)
  // wx.openUrl ({ url:url, complete: console.log } )
  wx.navigateTo({
    url: '/pages/AD/ad?url='+url,
  })
},
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    let that=this;
    this.setData({pageHeight:app.globalData.windowHeight})// console.log(this.data.pageHeight)
    this.setData({pageWidth:app.globalData.windowWidth})// console.log(this.data.pageWidth)
    this.$wuxBackdrop = $wuxBackdrop()
    wx.showLoading({
      title: 'loading...',
    })
    //加载四篇文章
    let aList=await util.queryDBbyLimt('Articles',begin,step,{visibility:true});
    let adList=await util.queryDbById('Settings','_ad_list').noticeList
    // console.log(articleList);
    // console.log(adList)
    //用户数据管理
    // let userPriInfo=await util.queryDbById('UserPrivateInfo','bb4c25156261752300d2ebbd49f05d7a')
    let openid=await util.getOpenID();
    openid=openid.result.openid
    let userPriInfo=await util.queryDbByOpenId('UserPrivateInfo',openid)//通过openid查询
    // var userPriInfo =await util.queryDbAll('UserPrivateInfo')
    userPriInfo=userPriInfo[0];
    // console.dir(userPriInfo)
    if(userPriInfo){//userPriInfalse fo
      app.globalData.hasUserInfo=true
      app.globalData.userInfo.openId=openid
      app.globalData.presentTheme=app.globalData.themes[userPriInfo.theme]
      console.log("当前主题",app.globalData.presentTheme)
      // console.log("剩余可用（付费）次数："+userPriInfo.remaining_times)
      app.globalData.userInfo.remainingTimes=userPriInfo.remaining_times
      // console.log("皮肤分析指标："+userPriInfo.skinAnalyzeInspect)
      app.globalData.userInfo.skinAnalyzeInspect=userPriInfo.skinAnalyzeInspect
      app.globalData.userInfo.detectAllow=await util.isDetectAllow()
      // console.log(this.globalData.userInfo.detectAllow)
      // let userData=await util.queryDbByLookup('UserPublicInfo','UserPrivateInfo','_openid','_openid')
      // userData=userData.data[0];
      // this.globalData.userInfo.nickName=userData.avatarUrl;
      // this.globalData.userInfo.avatarUrl=userData.nick_name;
      // this.globalData.userInfo.remainingTimes=userData.userInfo.remaining_times;
      // this.globalData.userInfo.skinAnalyzeInspect=userData.userInfo.skinAnalyzeInspect;
      let userPublicInfo=await util.queryDbByOpenId('UserPublicInfo',openid)//通过openid查询
      // var userPriInfo =await util.queryDbAll('UserPrivateInfo')
      userPublicInfo=userPublicInfo[0];
      // // console.log(userPublicInfo)
      app.globalData.userInfo.avatarUrl=userPublicInfo.avatarUrl;
      app.globalData.userInfo.nickName=userPublicInfo.nick_name;
      this.setData({
        ['userInfo.avatarUrl']:app.globalData.userInfo.avatarUrl,
        ['userInfo.nickName']:app.globalData.userInfo.nickName,
        ['userInfo.bgc']:app.globalData.presentTheme.lightBgColor,
        presentTheme:app.globalData.presentTheme,
        themeName:getApp().globalData.presentTheme.lightColor.match(/wux-(\S*)/)[1],
        btnValue:(userPriInfo.theme==0)?false:true,
        fans:userPublicInfo.fans.length,
        shop:userPriInfo.shop_history.length,
        follows:userPublicInfo.subscribe.length,
        stars:userPriInfo.stars.length,
      })
    //   if (typeof that.getTabBar === 'function' &&
    //   that.getTabBar()) {
    //   that.getTabBar().setData({
    //     current:0,
    //     theme:getApp().globalData.presentTheme.midColor.match(/wux-(\S*)/)[1],
    //     themeName:getApp().globalData.presentTheme.deepColor.match(/wux-(\S*)/)[1],
    //   })
    // }
    }else{
      //用户还未使用过本小程序,需要初始化账户
      app.globalData.hasUserInfo=false
      console.log("用户"+app.globalData.userInfo+"\n新用户需注册")
    }

    this.setData({
      articleList:aList,
      noticeList:adList,
    })
    getApp().globalData.showArticleList=aList;//赋给全局数组
    console.log(this.data.articleList)
    that.getTabBar().setData({
      current:0,
      theme:getApp().globalData.presentTheme.midColor.match(/wux-(\S*)/)[1],
      themeName:getApp().globalData.presentTheme.deepColor.match(/wux-(\S*)/)[1],
    })
    wx.hideLoading({
      success:function(){
        that.setData({show:true})
      }
    })
    // if(app.globalData.hasUserInfo){
    // let id=(await util.getOpenID()).result.openid;
    // console.log(id);
    // let uInfo=(await util.queryDbByOpenId('UserPublicInfo',id))[0] ;
    // // util.updateAvatar(id);
    // console.log(uInfo)
    //   app.globalData.userInfo.avatarUrl=uInfo.avatarUrl;
    //   app.globalData.userInfo.nickName=uInfo.nick_name;
    //   this.setData({['userInfo.avatarUrl']:uInfo.avatarUrl,['userInfo.nickName']:uInfo.nick_name})
    // }
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
async onRefresh() {
    console.log('onRefresh')
    // $startWuxRefresher()
    //加载四篇文章
    let aList=await util.queryDBbyLimt('Articles',0,4,{visibility:true});
    let adList=await util.queryDbById('Settings','_ad_list').noticeList
    // console.log(articleList);
    // console.log(adList)
    this.setData({
      articleList:aList,
      noticeList:adList
    })
    getApp().globalData.showArticleList=aList;//赋给全局数组
    setTimeout(() => {
      // this.setData({ items: getList() })
      $stopWuxRefresher()
    }, 700)
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

    if (typeof this.getTabBar === 'function' &&
        this.getTabBar()) {
        this.getTabBar().setData({
          current: 0
        })
     }

     let app=getApp();
     this.setData({
      ['userInfo.avatarUrl']:app.globalData.userInfo.avatarUrl,
      ['userInfo.nickName']:app.globalData.userInfo.nickName,
     })
     
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom:async function () {
    //跳跃加载
    wx.showToast({
      icon:'loading',
      title: '加载中...',
    })
    begin+=step;
    var addList=await util.queryDBbyLimt('Articles',begin,step,{visibility:true});

    console.log(addList)
    wx.hideToast({})
    if(addList==false){
      // wx.showToast({
      //   icon:'none',
      //   title: '暂无更多内容',
      //   duration:1500
      // })
      this.setData({msg:'已全部加载完毕'})
    }else{   
       // this.data.articleList.concat(addList);//追加数组
       getApp().globalData.showArticleList=getApp().globalData.showArticleList.concat(addList)
      this.setData({
        articleList:this.data.articleList.concat(addList)
      })
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  },
  openPerson:function(){
    // wx.showModal({
    //   title:'hello',
    // })
    // this.fadeIn()
    this.retain()
    // wx.showToast({
    //   icon:'none',
    //   title: '进入个人中心',
    //   duration:1000,success:()=>{this.switchToPerson()}
    // })
  },
  initAccount:function(){
    // let app=getApp();
    wx.showToast({
      icon:'none',
      title: '请先登录',
      duration:1000,
      success:()=>{
        this.switchToPerson()
      }
    })
    // util.initAccount().then(()=>{
    //   this.setData({['userInfo.avatarUrl']:app.globalData.userInfo.avatarUrl,['userInfo.nickName']:app.globalData.userInfo.nickName})
    // })
  },
  navToCollect(){
    wx.showToast({
      title: '此功能测试中',
      icon: 'error',
      duration: 1500
    })
  },
  navToMyArticle(){
    wx.navigateTo({
      url: '/pages/person/myArticle/myArticle'
    })
  },
  switchToPerson:function(){
    wx.switchTab({
      url: '/pages/person/person',
    })
  }
  ,
  onClick(e) {
    console.log('onClick', e.detail)
    switch(e.detail.index) {
      case 0:
        this.camera()
        break;
      case 1:
        this.image()
        break;
      case 2:
        this.create()
        break;
      }
  },
  image:function(){
    // wx.showModal({
    //   title:'image',
    //   cancelColor: '#000',
    // })
    // this.navToEditor()
    this.navToAddArticle()
  },
  camera:function(){
    // wx.showModal({
    //   title:'camera',//即将前往拍照
    //   cancelColor: '#000',
    // })
    // this.navToEditor()
    this.navToAddArticle()
  },
  create:function(){
    // wx.showModal({
    //   title:'create',
    //   cancelColor: '#000',
    // })
    // this.navToEditor()
    this.navToAddArticle()
  },
  // navToEditor(){
  //   wx.navigateTo({
  //     url: '/components/editor/editor',
  //   })
  // },
  navToAddArticle(){
    wx.navigateTo({
      url: '/pages/article/addArticle',
    })
  },
  navToArticle(e){
    // console.log(e.target);//点击的view
    // console.log(e.currentTarget);//有绑定事件的view
    var pageUrl='/pages/article/readArticle';
    var articleid=e.currentTarget.dataset['articleid']
    // wx.showToast({
    //   icon:'none',
    //   title: data.detail.dataset,
    // })
    wx.navigateTo({
      url: `${pageUrl}?id=${articleid}`,
    })
    // console.log(`${url}?id=${articleid}`)
   }
})